// 功能点：
// 1. 热搜
// 2. 历史搜索
// 3. 模糊搜索
// 4. 搜索与渲染
// 5. 播放MV
// 6. MV评论



// 1. 热搜



// 热门搜索的4个item
let hotSearch = document.querySelector('.hot-search-box').children;
// 搜索框
const searchFocus = document.querySelector('.search');
// 相关搜索结果盒子
const relevantBox = document.querySelector('.relevant-result-box');
// 单曲搜索结果显示区域
const resultMiddleArea = document.querySelector('.result-middle-area');

console.log('在这' + topNavSpan);

// 获取热搜
ajaxRequest({
    url: `${defaultUrlHeader}/search/hot/detail`,

    success: function (responseText) {
        console.log('获取热搜成功');

        // 渲染热搜item
        hotSearchRender(responseText.data);
    },

    error: function (xhr) {
        console.log('获取热搜失败');
        console.log(xhr.readyState);
        console.log(xhr.status);
    }
});



// 渲染热搜item
function hotSearchRender(obj) {
    for (let i = 0; i < 5; i++) {
        hotSearch[i].innerHTML = obj[i].searchWord;
    }
}



// 点击热搜item可直接进行搜索
for (let i = 0; i < 5; i++) {
    hotSearch[i].addEventListener('click', function () {
        searchFocus.value = hotSearch[i].innerHTML;
        let inputValue = searchFocus.value;

        // 搜索渲染
        searchAndRender(inputValue);
    })
}



// 2. 历史搜索



// 历史搜索盒子
const historySearchBox = document.querySelector('.history-search-box');
// 历史搜索ul
const historySearchUl = document.querySelector('.history-search');
// 清除按钮"x"
const clearRecordBtn = document.querySelector('.history-search-title').querySelector('span');
// 搜索放大镜
const searchBtn = document.querySelector('.search-btn');



// 点击搜索按钮，记录搜索内容
searchBtn.addEventListener('click', recordSearchContent)



// 记录搜索内容
function recordSearchContent() {
    // 渲染历史搜索
    showRecord();

    let inputValue = searchFocus.value;

    // 无输入则退出
    if (!inputValue) {
        return;
    }

    let arr = [];

    // 获取本地存储的历史记录
    let localItem = localStorage.getItem('searchRecord');
    arr = localItem ? JSON.parse(localItem) : [];

    // 判断输入的内容是否有存储
    let flag = false,
        arrLength = arr.length;

    for (let i = 0; i < arrLength; i++) {
        if (inputValue == arr[i]) {
            flag = true;
        }
    }

    // 如果有输入内容且不重复，则存储
    if (inputValue && !flag) {
        arr.unshift(inputValue);
        flag = false;
        // 把数组转化为字符串对象，再进行存储
        localStorage.setItem('searchRecord', JSON.stringify(arr));

        // 渲染历史搜索
        showRecord();
    }
}



// 渲染历史搜索
function showRecord() {

    // 选出当前li节点
    let localContent = JSON.parse(localStorage.getItem('searchRecord')) || [],
        historySearchItem = document.querySelectorAll('.history-search-item'),
        historySearchItemLength = historySearchItem.length,
        localContentLength = localContent.length;

    // 先删除原有的节点
    for (let i = 0; i < historySearchItemLength; i++) {
        historySearchUl.removeChild(historySearchItem[i]);
    }

    // 再创建新的li节点
    for (let i = 0; i < localContentLength; i++) {
        let recordLi = document.createElement('li');
        historySearchUl.appendChild(recordLi);

        recordLi.className = 'history-search-item';
        recordLi.innerHTML = localContent[i];
    }

    // 注意这里每个li（item）的声明已经无效了，要重新声明
    let historySearchLi = document.querySelectorAll('.history-search-item'),
        historySearchLiLength = historySearchLi.length;

    // 点击li节点，可进行搜索
    for (let i = 0; i < historySearchLiLength; i++) {
        historySearchLi[i].addEventListener('click', function () {
            let searchContent = historySearchLi[i].innerHTML;

            // 搜索渲染
            searchAndRender(searchContent);
        })
    }
}



// 点击删除所有历史记录
clearRecordBtn.addEventListener('click', () => {

    let historySearchItem = document.querySelectorAll('.history-search-item'),
        childrenLen = historySearchUl.children.length;

    // 删除节点
    for (let i = 0; i < childrenLen; i++) {
        historySearchUl.removeChild(historySearchItem[i]);
    }

    historySearchBox.style.display = 'none';

    // 删除本地存储
    localStorage.removeItem('searchRecord');
})



// 3. 模糊搜索



// 存储定时器的变量
var timer = null;



// 搜索框输入事件
searchFocus.addEventListener('input', function () {

    // 清除上一次开启的定时器
    clearTimeout(timer);

    let inputValue = this.value;

    // 如果用户没有输入内容，则隐藏搜索盒子，显示历史搜索盒子
    if (inputValue.length == 0 && historySearchUl.children.length !== 0) {
        // 渲染历史搜索
        showRecord();

        relevantBox.style.display = 'none';
        historySearchBox.style.display = 'block';
    } else {
        relevantBox.style.display = 'block';
        historySearchBox.style.display = 'none';
    }

    // 开启定时器
    timer = setTimeout(function () {
        // 获取模糊搜索结果
        ajaxRequest({
            url: `${defaultUrlHeader}/search/suggest`,

            data: {
                keywords: inputValue
            },

            success: function (responseText) {
                console.log('模糊搜索成功');
                console.log(responseText);

                // 获取响应内容中的单曲、歌单、专辑数组
                let songs = responseText.result.songs,
                    playlists = responseText.result.playlists,
                    albums = responseText.result.albums;

                // 将搜索结果渲染搜索item
                displayResult(songs, playlists, albums);
            },

            error: function (xhr) {
                console.log('模糊搜索失败');
                console.log(xhr.readyState);
                console.log(xhr.status);
            }
        });
    }, 500);
})



// 点击放大镜搜索后，隐藏模糊搜索盒子、历史记录盒子
searchBtn.addEventListener('click', () => {
    historySearchBox.style.display = 'none';
    relevantBox.style.display = 'none';
})



// 输入框失去焦点
searchFocus.addEventListener('blur', function () {
    if (this.value == '') {
        historySearchBox.style.display = 'block';
        relevantBox.style.display = 'none';
    } else {
        historySearchBox.style.display = 'none';
        relevantBox.style.display = 'block';
    }
})



// 输入框获得焦点
searchFocus.addEventListener('focus', function () {
    // 渲染历史搜索
    showRecord();

    // 如果获得焦点时输入为空，则显示历史搜索盒子
    if (this.value == '' && historySearchUl.children.length) {
        historySearchBox.style.display = 'block';
        relevantBox.style.display = 'none';
    } else if (this.value !== '') {
        historySearchBox.style.display = 'none';
        relevantBox.style.display = 'none';
    }
})



// 模糊搜索歌曲item
let songItems = document.querySelectorAll('.relevant-songs-item');
// 模糊搜索歌单item
let playlistItems = document.querySelectorAll('.relevant-playlists-item');
// 模糊搜索专辑item
let albumItems = document.querySelectorAll('.relevant-albums-item');



// 将搜索结果渲染搜索item
function displayResult(songs, playlists, albums) {

    // 渲染单曲
    if (songs !== undefined) {

        let songsLength = songs.length;

        for (let i = 0; i < songsLength; i++) {

            if (songsLength < 4) {
                for (let i = songsLength; i < 4; i++) {
                    songItems[i].style.display = 'none';
                }
            }

            songItems[i].style.display = 'block';
            songItems[i].innerHTML = songs[i].name + ' ' + songs[i].artists[0].name;

            // 点击item，可以进行搜索
            songItems[i].addEventListener('click', function () {
                searchFocus.value = songItems[i].innerHTML;
                let inputValue = searchFocus.value;

                // 搜索渲染
                searchAndRender(inputValue);

                relevantBox.style.display = 'none';
            })
        }
    } else {
        songItems[0].style.display = 'block';
        songItems[0].innerHTML = '未搜索到单曲相关结果';

        for (let i = 1; i < 4; i++) {
            songItems[i].style.display = 'none';
        }
    }

    // 渲染歌单
    if (playlists !== undefined) {

        let playlistsLength = playlists.length;

        for (let i = 0; i < playlistsLength; i++) {

            if (playlistsLength < 2) {
                for (let i = playlistsLength; i < 2; i++) {
                    playlistItems[i].style.display = 'none';
                }
            }

            playlistItems[i].style.display = 'block';
            playlistItems[i].innerHTML = playlists[i].name;

            // 点击item，可以进行搜索
            playlistItems[i].addEventListener('click', function () {
                searchFocus.value = playlistItems[i].innerHTML;
                let inputValue = searchFocus.value;

                // 搜索渲染
                searchAndRender(inputValue);

                relevantBox.style.display = 'none';
            })
        }
    } else {
        playlistItems[0].style.display = 'block';
        playlistItems[0].innerHTML = '未搜索到歌单相关结果';
        playlistItems[1].style.display = 'none';
    }


    // 渲染专辑
    if (albums !== undefined) {

        let albumsLength = albums.length;

        for (let i = 0; i < albumsLength; i++) {

            if (albumsLength < 2) {
                for (let i = albumsLength; i < 2; i++) {
                    albumItems[i].style.display = 'none';
                }
            }

            albumItems[i].style.display = 'block';
            albumItems[i].innerHTML = albums[i].name;

            // 点击item，可以进行搜索
            albumItems[i].addEventListener('click', function () {
                searchFocus.value = albumItems[i].innerHTML;
                let inputValue = searchFocus.value;

                // 搜索渲染
                searchAndRender(inputValue);

                relevantBox.style.display = 'none';
            })
        }
    } else {
        albumItems[0].style.display = 'block';
        albumItems[0].innerHTML = '未搜索到专辑相关结果';
        albumItems[1].style.display = 'none';
    }
}



// 4. 搜索与渲染



// 导航栏——单曲
const navSong = document.querySelector('.result-nav-songs');
// 导航栏——歌单
const navPlaylist = document.querySelector('.result-nav-playlists');
// 导航栏——专辑
const navAlbum = document.querySelector('.result-nav-albums');
// 导航栏——MV
const navMv = document.querySelector('.result-nav-mvs');
// 单曲搜索区域
const resultMainAreaSongs = document.querySelector('.result-main-area-songs');
// 歌单搜索结果区域
const resultMainAreaPlaylists = document.querySelector('.result-main-area-playlists');
// 专辑搜索结果区域
const resultMainAreaAlbums = document.querySelector('.result-main-area-albums');
// MV搜索结果区域
const resultMainAreaMvs = document.querySelector('.result-main-area-mvs');
// 无搜索记录
const noResult = document.querySelector('.no-result');
// MV播放页面
const mvDisplayArea = document.querySelector('.mv-display-area');
// video
let mvVideo = document.querySelector('.mv-video');
// 音乐信息界面
const songDisplayArea = document.querySelector('.song-display-area');



// 点击放大镜，进行搜索
searchBtn.addEventListener('click', () => {
    let inputValue = searchFocus.value;

    // 搜索渲染
    searchAndRender(inputValue);
})



// 搜索渲染
function searchAndRender(inputValue) {
    // 选中“单曲”item
    navSong.style.color = '#31C27C';
    navPlaylist.style.color = '#111';
    navAlbum.style.color = '#111';
    navMv.style.color = '#111';
    // 默认显示单曲结果页面
    resultMainAreaSongs.style.display = 'block';
    resultMainAreaPlaylists.style.display = 'none';
    resultMainAreaAlbums.style.display = 'none';
    resultMainAreaMvs.style.display = 'none';
    noResult.style.display = 'none';
    mvDisplayArea.style.display = 'none';
    songDisplayArea.style.display = 'none';
    userInfPage.style.display = 'none';
    // 搜索单曲
    ajaxRequest({
        url: `${defaultUrlHeader}/search`,

        data: {
            keywords: inputValue
        },

        success: function (responseText) {
            console.log('搜索单曲成功');
            console.log(responseText);

            // 默认显示单曲搜索结果区域
            resultMiddleArea.style.display = 'block';

            // 将搜索结果渲染至单曲区域
            searchRenderSongs(responseText.result.songs);
        },

        error: function (xhr) {
            console.log('搜索单曲失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    });

    // 搜索歌单
    ajaxRequest({
        url: `${defaultUrlHeader}/search`,

        data: {
            keywords: inputValue,
            type: 1000
        },

        success: function (responseText) {
            console.log('搜索歌单成功');
            console.log(responseText);

            // 默认显示单曲搜索结果区域
            resultMiddleArea.style.display = 'block';

            // 将搜索结果渲染至单曲区域
            searchRenderPlaylists(responseText.result.playlists);
        },

        error: function (xhr) {
            console.log('搜索歌单失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    });

    // 搜索专辑
    ajaxRequest({
        url: `${defaultUrlHeader}/search`,

        data: {
            keywords: inputValue,
            type: 10
        },

        success: function (responseText) {
            console.log('搜索专辑成功');
            console.log(responseText);

            // 默认显示单曲搜索结果区域
            resultMiddleArea.style.display = 'block';

            // 将搜索结果渲染至专辑区域
            searchRenderAlbums(responseText.result.albums);
        },

        error: function (xhr) {
            console.log('搜索专辑失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    });

    // 搜索MV
    ajaxRequest({
        url: `${defaultUrlHeader}/search`,

        data: {
            keywords: inputValue,
            type: 1004
        },

        success: function (responseText) {
            console.log('搜索MV成功');
            console.log(responseText);

            // 默认显示单曲搜索结果区域
            resultMiddleArea.style.display = 'block';

            // 将搜索结果渲染至MV区域
            searchRenderMvs(responseText.result.mvs);
        },

        error: function (xhr) {
            console.log('搜索MV失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    });

    // 点击“单曲”，切换单曲搜索结果页面
    navSong.addEventListener('click', function () {
        this.style.color = '#31C27C';
        navPlaylist.style.color = '#111';
        navAlbum.style.color = '#111';
        navMv.style.color = '#111';

        // 隐藏其他搜索区域，显示单曲搜索结果区域
        resultMainAreaSongs.style.display = 'block';
        resultMainAreaPlaylists.style.display = 'none';
        resultMainAreaAlbums.style.display = 'none';
        resultMainAreaMvs.style.display = 'none';
        noResult.style.display = 'none';
        mvDisplayArea.style.display = 'none';
        songDisplayArea.style.display = 'none';
        mvVideo.pause();
    })

    // 点击“歌单”，切换歌单搜索结果页面
    navPlaylist.addEventListener('click', function () {
        this.style.color = '#31C27C';
        navSong.style.color = '#111';
        navAlbum.style.color = '#111';
        navMv.style.color = '#111';

        // 隐藏其他搜索区域，显示歌单搜索结果区域
        resultMainAreaPlaylists.style.display = 'block';
        resultMainAreaSongs.style.display = 'none';
        resultMainAreaAlbums.style.display = 'none';
        resultMainAreaMvs.style.display = 'none';
        noResult.style.display = 'none';
        mvDisplayArea.style.display = 'none';
        songDisplayArea.style.display = 'none';
        mvVideo.pause();
    })

    // 点击“专辑”，切换专辑搜索结果页面
    navAlbum.addEventListener('click', function () {
        this.style.color = '#31C27C';
        navSong.style.color = '#111';
        navPlaylist.style.color = '#111';
        navMv.style.color = '#111';

        // 隐藏其他搜索区域，显示歌单搜索结果区域
        resultMainAreaAlbums.style.display = 'block';
        resultMainAreaSongs.style.display = 'none';
        resultMainAreaPlaylists.style.display = 'none';
        resultMainAreaMvs.style.display = 'none';
        noResult.style.display = 'none';
        mvDisplayArea.style.display = 'none';
        songDisplayArea.style.display = 'none';
        mvVideo.pause();
    })

    // 点击“MV”，切换MV搜索结果页面
    navMv.addEventListener('click', function () {
        this.style.color = '#31C27C';
        navSong.style.color = '#111';
        navPlaylist.style.color = '#111';
        navAlbum.style.color = '#111';

        // 隐藏其他搜索区域，显示MV搜索结果区域
        resultMainAreaMvs.style.display = 'block';
        resultMainAreaSongs.style.display = 'none';
        resultMainAreaPlaylists.style.display = 'none';
        resultMainAreaAlbums.style.display = 'none';
        mvDisplayArea.style.display = 'none';
        songDisplayArea.style.display = 'none';
        mvVideo.pause();
    })
}



// 单曲名
let resultSongs = document.querySelector('.result-songs-box').querySelectorAll('li');
// 单曲的歌手
let resultArtists = document.querySelector('.result-artists-box').querySelectorAll('li');
// 单曲的专辑
let resultAlbums = document.querySelector('.result-albums-box').querySelectorAll('li');



// 将搜索结果渲染至单曲区域
function searchRenderSongs(songs) {

    let songsLength = songs.length >= 10 ? 10 : songs.length;

    for (let i = 0; i < songsLength; i++) {

        // 单曲名
        resultSongs[i].innerHTML = songs[i].name;

        // 检查歌手个数
        if (songs[i].artists.length == 2) {
            resultArtists[i].innerHTML = `${songs[i].artists[0].name} ${songs[i].artists[1].name}`;
        } else {
            resultArtists[i].innerHTML = songs[i].artists[0].name;
        }

        // 专辑名
        resultAlbums[i].innerHTML = songs[i].album.name;

        // 点击单曲item转至音乐信息页面
        resultSongs[i].addEventListener('click', () => {
            songDisplayArea.style.display = 'block';
            resultMainAreaSongs.style.display = 'none';

            // 获取单曲详细信息
            songDetail(songs[i].id);
            // 获取单曲评论
            songComments(songs[i].id);
        })
    }
}



// 歌单图片item
let resultPlaylistPictures = document.querySelector('.result-playlists-pictures-box').querySelectorAll('li');
// 歌单名item
let resultPlaylistNames = document.querySelector('.result-playlists-names-box').querySelectorAll('li');
// 歌单创建人item
let resultPlaylistUsers = document.querySelector('.result-playlists-users-box').querySelectorAll('li');
// 歌单播放量item
let resultPlaylistCounts = document.querySelector('.result-playlists-counts-box').querySelectorAll('li');



// 将搜索结果渲染至歌单区域
function searchRenderPlaylists(playlists) {

    let playlistsLength = playlists.length >= 10 ? 10 : playlists.length;

    for (let i = 0; i < playlistsLength; i++) {
        resultPlaylistPictures[i].style.backgroundImage = `url(${playlists[i].coverImgUrl})`;
        resultPlaylistNames[i].innerHTML = playlists[i].name;
        resultPlaylistUsers[i].innerHTML = playlists[i].creator.nickname;
        // 转化播放量
        resultPlaylistCounts[i].innerHTML = transformCounts(playlists[i].playCount);
    }
}



// 专辑图片item
let resultAlbumPictures = document.querySelector('.result-albums-pictures-box').querySelectorAll('li');
// 专辑名item
let resultAlbumNames = document.querySelector('.result-albums-names-box').querySelectorAll('li');
// 专辑歌手item
let resultAlbumUsers = document.querySelector('.result-albums-users-box').querySelectorAll('li');
// 专辑发行时间item
let resultAlbumTypes = document.querySelector('.result-albums-types-box').querySelectorAll('li');



// 将搜索结果渲染至专辑区域
function searchRenderAlbums(albums) {

    let albumsLength = albums.length >= 10 ? 10 : albums.length;

    for (let i = 0; i < albumsLength; i++) {

        resultAlbumPictures[i].style.backgroundImage = `url(${albums[i].blurPicUrl})`;
        resultAlbumNames[i].innerHTML = albums[i].name;

        // 检查歌手个数
        if (albums[i].artists.length == 2) {
            resultAlbumUsers[i].innerHTML = `${albums[i].artists[0].name} ${albums[i].artists[1].name}`;
        } else {
            resultAlbumUsers[i].innerHTML = albums[i].artists[0].name;
        }

        resultAlbumTypes[i].innerHTML = albums[i].type;
    }
}



// MV item
let mvItem = document.querySelectorAll('.result-mvs-item');
// MV图片
let mvPictures = document.querySelector('.result-main-area-mvs').querySelectorAll('a');
// MV名字
let mvNames = document.querySelector('.result-main-area-mvs').querySelectorAll('.mv-name');
// MV歌手
let mvPlayers = document.querySelector('.result-main-area-mvs').querySelectorAll('.mv-player');
// 评论框
let commentText = document.querySelector('.mv-display-area').querySelector('.comment-text');
// 提交按钮
let commentBtn = document.querySelector('.mv-display-area').querySelector('.comment-button');
// 删除按钮
let deleteMvCommentBtn = document.querySelector('.delete-mv-comment-btn');
// 无内容提示
let noMvCommentTip = document.querySelector('.mv-display-area').querySelector('.no-comment-tip');



// 将搜索结果渲染至MV区域
function searchRenderMvs(mvs) {

    if (mvs == null) {
        resultMainAreaMvs.style.display = 'none';
        noResult.style.display = 'block';
    } else {

        let mvsLength = mvs.length >= 12 ? 12 : mvs.length;

        for (let i = 0; i < mvsLength; i++) {

            mvItem[i].style.display = 'block';

            // 如果MV个数不足12，则隐藏剩下的MV item
            if (mvs.length < 12) {
                for (let i = mvsLength; i < 12; i++) {
                    mvItem[i].style.display = 'none';
                }
            }

            mvPictures[i].style.backgroundImage = `url(${mvs[i].cover})`;
            mvNames[i].innerHTML = mvs[i].name;

            // 检查歌手个数
            if (mvs[i].artists.length == 2) {
                mvPlayers[i].innerHTML = `${mvs[i].artists[0].name} ${mvs[i].artists[1].name}`;
            } else {
                mvPlayers[i].innerHTML = mvs[i].artistName;
            }
        }

        // 点击MV item，跳转至MV播放页面
        for (let i = 0; i < mvsLength; i++) {

            mvItem[i].addEventListener('click', function () {

                mvDisplayArea.style.display = 'block';
                resultMainAreaMvs.style.display = 'none';

                // 获取MV地址
                ajaxRequest({
                    url: `${defaultUrlHeader}/mv/url`,

                    data: {
                        id: mvs[i].id
                    },

                    success: function (responseText) {
                        console.log('请求成功');
                        console.log(responseText);

                        // MV地址
                        mvVideo.src = responseText.data.url;

                        // 渲染MV信息
                        mvInformation(mvs[i]);
                        // 获取MV评论
                        getMvComments(mvs[i].id);
                    },

                    error: function (xhr) {
                        console.log('请求失败');
                        console.log(xhr.readyState);
                        console.log(xhr.status);
                    }
                });
            })
        }
    }
}



// 获取MV评论
function getMvComments(mvId) {
    // 获取MV评论
    ajaxRequest({
        url: `${defaultUrlHeader}/comment/mv`,

        data: {
            id: mvId,
            limit: 100
        },

        success: function (responseText) {
            console.log('获取MV评论成功');
            console.log(responseText);

            // 渲染MV评论
            mvComments(responseText.comments, responseText.hotComments, responseText.userId);
            // 发布评论
            postMyComment(mvId);
            // 删除评论
            deleteMyComment(mvId);
        },

        error: function (xhr) {
            console.log('获取MV评论失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    });
}



// 5. 播放MV



// mv标题
let mvTitle = document.querySelector('.mv-title');
// mv播放量
let mvPlaycounts = document.querySelector('.mv-counts');



// 渲染MV信息
function mvInformation(mv) {
    // 检查歌手个数
    if (mv.artists.length == 2) {
        mvTitle.innerHTML = `${mv.name} - ${mv.artists[0].name} ${mv.artists[1].name}`;
    } else {
        mvTitle.innerHTML = `${mv.name} - ${mv.artistName}`;
    }
    // 播放量
    mvPlaycounts.innerHTML = `播放量：${mv.playCount}`;
}



// 6. MV评论



// MV评论数
let mvCommentCounts = document.querySelector('.comment-counts');
// 评论item
let commentItems = document.querySelector('.mv-display-area').querySelectorAll('.hot-comments');
// 评论用户头像
let commentUserHead = document.querySelector('.mv-display-area').querySelectorAll('.comment-user-head');
// 评论用户昵称
let commentUserName = document.querySelector('.mv-display-area').querySelectorAll('.comment-user-name');
// 评论时间
let commentDate = document.querySelector('.mv-display-area').querySelectorAll('.comment-date');
// 评论内容
let commentContent = document.querySelector('.mv-display-area').querySelectorAll('.comment-content');
// 评论点赞
let commentLike = document.querySelector('.mv-display-area').querySelectorAll('.comment-like');
// "精彩评论"
let hotCommentTitle = document.querySelector('.hot-comments-title');



// 渲染MV评论
function mvComments(comments, hotComments, userId) {

    let commentsLength = comments.length,
        hotCommentsLength = hotComments.length;

    // 判断评论数
    if (commentsLength) {
        mvCommentCounts.innerHTML = `共${commentsLength}条评论`;
    } else {
        mvCommentCounts.innerHTML = `共0条评论`;
    }

    // 先隐藏所有的评论item盒子
    for (let i = 0; i < 5; i++) {
        commentItems[i].style.display = 'none';
    }

    // 优先显示热评，热评数不足5则用全部评论补全
    if (hotComments && hotCommentsLength >= 5) {
        // 渲染精彩评论
        commentDisplay(hotComments, 5);
    } else if (hotCommentsLength > 0 && hotCommentsLength < 5) {
        // 渲染精彩评论
        commentDisplay(hotComments, hotCommentsLength);
    } else if (comments && commentsLength > 0) {

        // 把"精彩评论"改为"全部评论"，但只显示五条
        hotCommentTitle.innerHTML = '全部评论';

        for (let i = 0; i < commentsLength; i++) {
            // 无精彩评论
            commentItems[i].style.display = 'block';
            commentUserHead[i].style.backgroundImage = `url(${comments[i].user.avatarUrl})`;
            commentUserName[i].innerHTML = comments[i].user.nickname;
            commentDate[i].innerHTML = comments[i].timeStr;
            commentContent[i].innerHTML = comments[i].content;
            commentLike[i].innerHTML = `${comments[i].likedCount}人觉得很赞`;
        }
    } else {
        // 无评论
        commentItems[0].style.display = 'block';
        commentContent[0].innerHTML = '当前歌曲暂无评论';
    }

    // 判断用户是否有在此MV下面评论
    if (commentsLength) {
        for (let i = 0; i < commentsLength; i++) {
            if (comments[i].user.userId == userId) {
                // 显示"我的评论"盒子并进行渲染
                myMvComment.style.display = 'block';
                myHead.style.backgroundImage = `url(${comments[i].user.avatarUrl})`;
                myNickname.innerHTML = comments[i].user.nickname;
                myDate.innerHTML = comments[i].timeStr;
                myContent.innerHTML = comments[i].content;
                myLike.innerHTML = `${comments[i].likedCount}人觉得很赞`;
            }
        }
    }
}



// 渲染精彩评论
function commentDisplay(hotComments, length) {
    for (let i = 0; i < length; i++) {
        commentItems[i].style.display = 'block';
        commentUserHead[i].style.backgroundImage = `url(${hotComments[i].user.avatarUrl})`;
        commentUserName[i].innerHTML = hotComments[i].user.nickname;
        commentDate[i].innerHTML = hotComments[i].timeStr;
        commentContent[i].innerHTML = hotComments[i].content;
        commentLike[i].innerHTML = `${hotComments[i].likedCount}人觉得很赞`;
    }
}



// "我的评论"盒子
let myMvComment = document.querySelector('.mv-display-area').querySelector('.my-comment');
// 我的头像
let myHead = document.querySelector('.mv-display-area').querySelector('.my-comment-head');
// 我的昵称
let myNickname = document.querySelector('.mv-display-area').querySelector('.my-comment-name');
// 我的评论时间
let myDate = document.querySelector('.mv-display-area').querySelector('.my-comment-date');
// 我的评论内容
let myContent = document.querySelector('.mv-display-area').querySelector('.my-comment-content');
// 我的评论点赞
let myLike = document.querySelector('.mv-display-area').querySelector('.my-comment-like');



// 发布评论
function postMyComment(mvId) {
    commentBtn.addEventListener('click', () => {

        let commentValue = commentText.value;

        if (commentValue !== '') {
            // 发布评论请求
            ajaxRequest({
                url: `${defaultUrlHeader}/comment`,

                data: {
                    t: 1,
                    type: 1,
                    id: mvId,
                    content: commentValue
                },

                success: function (responseText) {
                    console.log('发布评论成功');
                    console.log(responseText);

                    // 显示用户发布的内容
                    mvCommentRender(responseText.comment);
                },

                error: function (xhr) {
                    console.log('发布评论失败');
                    console.log(xhr.readyState);
                    console.log(xhr.status);
                }
            });
        } else {
            noMvCommentTip.style.display = 'block';

            commentText.addEventListener('focus', () => {
                noMvCommentTip.style.display = 'none';
            })
        }
    })
}



// 删除评论
function deleteMyComment(mvId) {
    deleteMvCommentBtn.addEventListener('click', () => {
        ajaxRequest({
            url: `${defaultUrlHeader}/comment`,

            data: {
                t: 0,
                type: 1,
                id: mvId,
                commentId: myContent.getAttribute('data-mvCommentId')
            },

            success: function (responseText) {
                console.log('删除mv评论成功');
                console.log(responseText);

                // 清空mv评论内容
                deleteMvComment();
            },

            error: function (xhr) {
                console.log('删除mv评论失败');
                console.log(xhr.readyState);
                console.log(xhr.status);
            }
        })
    })
}



// 显示并渲染用户评论内容
function mvCommentRender(comment) {
    commentText.innerHTML = '';
    myMvComment.style.display = 'block';
    myHead.style.backgroundImage = `url(${comment.user.avatarUrl})`;
    myNickname.innerHTML = comment.user.nickname;
    myDate.innerHTML = getTime(comment.time);
    myContent.innerHTML = comment.content;
    myLike.innerHTML = '0人觉得很赞';
    // 设置自定义属性，保存评论id
    myContent.setAttribute('data-mvCommentId', comment.commentId);
}



// 清空mv评论
function deleteMvComment() {
    // 移除自定义评论id属性
    myContent.removeAttribute('data-mvCommentId');
    myMvComment.style.display = 'none';
}